package com.zhou.common.lib.model;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.Map;

/**
 * @author li.ke
 * @date 2020/12/28
 */
@ApiModel("分页参数")
@Data
public class PageParam {

    @ApiModelProperty(value = "页数", example = "1", position = Integer.MAX_VALUE - 1)
    private Integer pageNo = 1;

    @ApiModelProperty(value = "每页大小", example = "10", position = Integer.MAX_VALUE)
    private Integer pageSize = 10;

    public IPage toPage() {
        return new Page(this.pageNo, this.pageSize);
    }

    /**
     * 筛选属性
     * 正序 aes 倒叙des
     */
    @ApiModelProperty(value = "key为排序字段,value 正序 asc 倒叙desc ")
    private Map<String, String> sortFieldMap;


    public static final Map<String, SFunction<BaseEntity, ?>> ORDER_COLUMNS = Maps.newHashMap();

    static {
        ORDER_COLUMNS.put("createdTime", BaseEntity::getCreatedTime);
    }

    public void sort(LambdaQueryWrapper<BaseEntity> queryWrapper) {
        if (sortFieldMap != null && sortFieldMap.size() > 0) {
            sortFieldMap.forEach((k, v) -> {
                if (k != null && v != null && ORDER_COLUMNS.containsKey(k)) {
                    queryWrapper.orderBy(true, v.equals("asc"), ORDER_COLUMNS.get(k));
                }
            });
        }
    }

    public static final Map<String, String> ORDER_COLUMNS_LIST = Maps.newHashMap();

    static {
        ORDER_COLUMNS_LIST.put("createdTime", "created_time");
    }

    public void sort(QueryWrapper<BaseEntity> queryWrapper) {
        if (sortFieldMap != null && sortFieldMap.size() > 0) {
            sortFieldMap.forEach((k, v) -> {
                if (k != null && v != null && ORDER_COLUMNS_LIST.containsKey(k)) {
                    queryWrapper.orderBy(true, v.equals("asc"), ORDER_COLUMNS_LIST.get(k));
                }
            });
        }
    }

}